package com.uroad.jilinpda.activity;

import android.annotation.TargetApi;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.uroad.jilinpda.R;
import com.uroad.jilinpda.adapter.BleListAdapter;
import com.uroad.jilinpda.bleactivation.BlueToothUtil;
import com.uroad.jilinpda.bleactivation.CmdHelper;
import com.uroad.jilinpda.bleactivation.CmdReceiveData;
import com.uroad.jilinpda.bleactivation.EtcUtils;
import com.uroad.jilinpda.bleactivation.TopUpBluetoothLeService;
import com.uroad.jilinpda.bleactivation.TopUpUtil;
import com.uroad.jilinpda.common.BaseActivity;
import com.uroad.jilinpda.common.Cmd;
import com.uroad.jilinpda.common.Code;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.modle.AuthgmMDL;
import com.uroad.jilinpda.modle.ModifyActivationMDL;
import com.uroad.jilinpda.net.JsonUtil;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.util.ToastUtil;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.webservice.ETCHandleWS;
import com.uroad.jilinpda.widget.OBULoadingDialog;
import com.uroad.jilinpda.widget.OBUTripDialog;
import com.uroad.lib.util.log.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
//import etc.obu.service.ConnectStatusCallback;
//import etc.obu.service.ServiceStatus;
//import etc.obu.service.deviceInit;

/**
 * obu激活界面 适配了聚力的obu：聚力OBU通道由A1变为A7 明文由20变为00
 */
public class ETCActivation2Activity extends BaseActivity implements Cmd, Code {
    private static final String TAG = "ETCActivationActivity";
    /**
     * 定义一个枚举，表示执行的步骤 CMD_A2 准备发送A2指令 CMD_CARD_BALANCE 准备发送查询余额指令
     * CMD_CARD_GET_0015 准备发送查询卡号指令 CMD_C4 准备发送C4指令 HTTP_C4 准备调用C4指令成功后的接口 CMD_C5
     * 准备发送C5指令 HTTP_FILE_0015 准备调用获取0015文件指令接口 CMD_FILE_0015 准备发送获取0015文件命令
     * HTTP_INIT_STORE 准备调用圈存初始化接口 CMD_INIT_STORE HTTP_STORE CMD_STORE
     * HTTP_STORE_CONFIRM
     * */
    private enum State {
        START,
        CMD_A2,
        CMD_TO_3F00,
        CMD_OBU_SYSTEM_INFO, //obu获取设备系统信息
        CMD_OBU_RANDOM, //obu获取随机数
        CMD_CARD_RANDOM, //获取卡随机数
        CMD_A5,//获取设备表面号
        CMD_OBU_CAR_INFO, //obu获取车辆信息文件
        CMD_CARD_GET_0016,//获取0016文件
        CMD_CARD_BALANCE,
        CMD_CARD_GET_0015,//获取卡号 （0015）
        CMD_CARD_PIN0,
        CMD_AUTHGM,
        CMD_GM_OBU_RANDOM,
        CMD_GM_CARD_RANDOM,
        CMD_GM_OBU_MODIFY_VEHICLE,
        CMD_GM_OBU_MODIFY_SYSTEM,
        CMD_GM_CARD_MODIFY_0016,
        CMD_GM_CARD_MODIFY_0015,
        CMD_OBU_MODIFY_VEHICLE,
        CMD_OBU_MODIFY_SYSTEM,
        CMD_CARD_MODIFY_0016,
        CMD_CARD_MODIFY_0015,
        CMD_C4,//C4指令
        HTTP_C4,
        CMD_C5, //C5指令
        HTTP_FILE_0015,
        CMD_FILE_0015,
        HTTP_INIT_STORE,
        CMD_INIT_STORE,
        HTTP_STORE,
        CMD_STORE,
        CMD_CARD_PIN3,
        CMD_CARD_PIN6,
        HTTP_STORE_CONFIRM
    }
    private Context mContext=this;
    @BindView(R.id.clTitleLayout)
    ConstraintLayout clTitleLayout;
    @BindView(R.id.iv_ring2)
    ImageView iv_ring2;
    @BindView(R.id.tv_step2)
    TextView tv_step2;
    @BindView(R.id.view_lien2)
    View lien2;
    @BindView(R.id.ivAnimation)
    ImageView ivAnimation;
    /** 布局 */
    @BindView(R.id.rl_ble_scan_list)
    RelativeLayout mRlBleList;
    @BindView(R.id.lv_ble_scan)
    RecyclerView mListView;

    //test
    @BindView(R.id.etOrderNo)
    EditText etOrderNo;

    private BleListAdapter mAdapter;
    private OBULoadingDialog loadingDialog;
    private OBUTripDialog tripDialog;
    /** 蓝牙工具类 */
    private BlueToothUtil mBlueToothUtil;
    private AnimationDrawable animationDrawable;
    /** 蓝牙连接service*/
    private TopUpBluetoothLeService mBluetoothLeService;
    /** 搜索到的设备列表名称 */
    private List<String> msgs = new ArrayList<String>();
    /** 搜索到的设备列表 */
    private List<BluetoothDevice> devicelist = new ArrayList<BluetoothDevice>();
    /** 判断service是否已经绑定 用来决定ondestory()中要不要解绑service*/
    private boolean isServiceBind = false;
    /** 是否走国密通道*/
    private boolean isGm = false;
    private State state = State.START;
    private String ticketid = "";
    private String deviceuuid = "";
    private String orderno = "";
    private String mDeviceMacAddress = "";
    private String mLastConnectedDevice = "";
    private String cardNo = "";
    private String cardBalance = "";
    private String cardArea = "";
    private String isrestart = "0";
    private String randomObu = "";
    private String randomCard = "";
    private String file0016 = "";
    private String file0015 = "";
    private String mSessionId = "";
    private String filevehicle = "";
    private String fileSystem = "";
    private String seno = "";
    private String contractedition = "";
    private String startstate = "0";
    private String instructions = "";
    private String instructionsmac = "";
    private String instructionresps = "";
    private String instructionrespsmac = "";
    private String plateNo = "";
    private String type = "";
    private boolean isActivationSuccess = false;
    private boolean isEndSureSuccess = false;
    //设备名
    private String deviceName = "";
    //是否是聚力OBU
    private boolean isJuLi = false;

    /**
     * 聚力使用的sdk做交互 需要单独写一套流程
     */
    //    private static deviceInit juLiDevice;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_etcactivation);
        setTitle("OBU激活");
        ButterKnife.bind(this);
        initData();
//        initBleSacnView();
        initListener();
    }

    private void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isGm = bundle.getBoolean("isgm");
            orderno = bundle.getString("orderno");
            String isneedpic = bundle.getString("isneedpic");
            type = bundle.getString("type");
            if (TextUtils.isEmpty(type)) {
                clTitleLayout.setVisibility(View.VISIBLE);
                if ("0".equalsIgnoreCase(isneedpic)) {
                    iv_ring2.setVisibility(View.GONE);
                    tv_step2.setVisibility(View.GONE);
                    lien2.setVisibility(View.GONE);
                }
            }else{
                clTitleLayout.setVisibility(View.GONE);
                setTitle("标签检测");
            }
        }
//        if (GlobalData.isDebug) {
//            etOrderNo.setVisibility(View.VISIBLE);
//        }
        loadingDialog = new OBULoadingDialog(this);
        tripDialog = new OBUTripDialog(this);
        mBlueToothUtil = new BlueToothUtil(this);
        animationDrawable = (AnimationDrawable) ivAnimation.getDrawable();
        mLastConnectedDevice = (String) SPUtils.get(this, GlobalData.Ble_Device_Mac, "");
        ticketid = (String) SPUtils.get(this, GlobalData.sp_ticketid, "");
        deviceuuid = (String) SPUtils.get(this, GlobalData.sp_deviceuuid, "");
        //        openActivity(ETCUploadPictureActivity.class);
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());// 注册广播
        CmdHelper.initFrameLen(92, mContext);// 先赋值92（艾特斯设备），后面会根据命令返回的内容修改长度
    }

    /** 初始化与蓝牙搜索设备相关的VIEW */
    private void initBleSacnView() {
        //        juLiDevice = new deviceInit(this);
        mRlBleList = (RelativeLayout) findViewById(R.id.rl_ble_scan_list);
        mListView = (RecyclerView) findViewById(R.id.lv_ble_scan);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mListView.setLayoutManager(manager);

        mAdapter = new BleListAdapter(mContext, msgs);
        mListView.setAdapter(mAdapter);
    }

    /** 蓝牙搜索列表的打开或关闭 */
    public void showSacnList(boolean b) {
        if (b) {
            // 打开搜索列表
            mRlBleList.setVisibility(View.VISIBLE);
        } else {
            // 关闭搜索列表
            mRlBleList.setVisibility(View.GONE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initListener() {
        tripDialog.setConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tripDialog.dismiss();
                finish();
            }
        });
        mAdapter.setOnItemClickListener(new BleListAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position) {
                mDeviceMacAddress = devicelist.get(position).getAddress();
                mBlueToothUtil.mDevice = devicelist.get(position);
                deviceName = devicelist.get(position).getName();
                isJuLi();
                toConnect();
                mBlueToothUtil.stopScanDevice();
                showSacnList(false);
                //                finish();

                // 保存连接的设备的mac（自动连接的相关代码）
                SPUtils.put(mContext, GlobalData.Ble_Device_Mac, mDeviceMacAddress);
            }
        });

        mBlueToothUtil.setBleStateCallback(new BlueToothUtil.BleStateCallback() {
            @Override
            public void startScan() {
                animationDrawable.start();
            }

            @Override
            public void stopScan() {
                animationDrawable.stop();
            }
        });
        //        juLiDevice.setConnectStatusCallback(juliCallback);
    }

    //    ConnectStatusCallback juliCallback = new ConnectStatusCallback() {
    //        @Override
    //        public void ConnectCb(ServiceStatus serviceStatus) {
    //            if (serviceStatus.getServiceCode() == 0) {
    //                LogUtils.e("connectDevice 成功 ");
    //                //                showInfo(serviceStatus.getServiceInfo());
    //                String result = mBluetoothLeService.juLisendTlvCmd(CMD_CARD_0016, 0, DIRECT_CMD_CARD_0016);
    //
    //            } else {
    //                //                showInfo(serviceStatus.getServiceInfo());
    //            }
    //        }
    //
    //        @Override
    //        public void ConnectLostCb() {
    //
    //        }
    //    };

    /**
     * 是否是聚力标签
     */
    private void isJuLi(){
        //聚力OBU
        isJuLi = EtcUtils.isJuLiObu(deviceName);
    }

    private void toConnect() {
        loadingDialog.setTips("正在连接");
        loadingDialog.show();
        connectBle();
    }

    private void juLiConnect() {
        //        juLiDevice.connectDevice(mBlueToothUtil.mDevice);
    }


    @Override
    protected void onResume() {
        super.onResume();
        startScan();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void startScan(){
        mBlueToothUtil.scanDevice(new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                /** 有些手机，扫描到同一个蓝牙设备也会不停的触发回调 因此，在这里要多做一个判断，如果重复就return*/
                for (BluetoothDevice mdl : devicelist) {
                    if (device.getAddress().equals(mdl.getAddress())) {
                        return;
                    }
                }
                if(isFinishing()|| TextUtils.isEmpty(device.getName())){
                    return;
                }
                /** 如果手机有记录上次连接的设备，那如果再次搜索到该设备就会自动连接 */
                if(!TextUtils.isEmpty(mLastConnectedDevice)) {
                    if (mLastConnectedDevice.equals(device.getAddress())) {
                        mDeviceMacAddress = device.getAddress();
                        mBlueToothUtil.mDevice = device;
                        deviceName = device.getName();
                        isJuLi();
                        showSacnList(false);//关闭蓝牙列表
                        //打开圈存界面并将要连接的蓝牙设备的MAC传给他
                        mBlueToothUtil.stopScanDevice();//停止扫描
                        toConnect();
                        //                        finish();
                        return;
                    }
                }
                LogUtil.i("","onLeScan:" + device.getAddress());
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        devicelist.add(device);
                        msgs.add(device.getName());
                        mAdapter.notifyDataSetChanged();
                        showSacnList(true);
                    }
                });
            }
        });
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BlueToothUtil.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BlueToothUtil.ACTION_RESP_INIT_SUCCESS);
        intentFilter.addAction(BlueToothUtil.ACTION_RECEIVCE_DATA_COMPLETE);
        intentFilter.addAction(BlueToothUtil.ACTION_STATE_DISCONNECTED);
        intentFilter.addAction(BlueToothUtil.ACTION_TRANSFER_EXCEPTIONS);
        return intentFilter;
    }

    /**
     * 连接蓝牙设备
     */
    private void connectBle() {
        if (TextUtils.isEmpty(mDeviceMacAddress)) {
            ToastUtil.showShort(mContext, "蓝牙地址为空，无法连接,请退出重试");
            return;
        }
        bindServiceConnAddress();
    }
    /**
     * 绑定Service,连接物理地址
     */
    private void bindServiceConnAddress() {
        Intent gattServiceIntent = new Intent(this,
                TopUpBluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection,
                Service.BIND_AUTO_CREATE);
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (isFinishing()) {
                return;
            }
            isServiceBind = true;
            mBluetoothLeService = ((TopUpBluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initializeBle()) {
                LogUtil.i("","Unable to initialize Bluetooth");
                // finish();
            }
            //            if (isJuLi) {
            //                mBluetoothLeService.setJuLiDevice(juLiDevice);
            //                juLiConnect();
            //            }else {
            // Automatically connects to the device upon successful start-up
            boolean b = mBluetoothLeService.connect(mDeviceMacAddress);
            LogUtil.i("","mServiceConnection:" + b);
            if (!b) {
                loadingDialog.dismiss();
                showTrip("蓝牙连接失败");
            }
            //            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            mBluetoothLeService = null;
        }

    };

    @Override
    protected void onStop() {
        super.onStop();
        if(isFinishing()) {
            if (isServiceBind) {
                unbindService(mServiceConnection);
            }
            unregisterReceiver(mGattUpdateReceiver);
            mBlueToothUtil.stopScanDevice();
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
            if (tripDialog.isShowing()) {
                tripDialog.dismiss();
            }
            //            if (mBluetoothLeService != null) {
            //                mBluetoothLeService.sendCmd(CMD_C3);
            //            }
        }
    }

    private void errorUpload(String errormsg){
        doRequest(ETCHandleWS.upload,
                ETCHandleWS.uploadParams(orderno, errormsg),ETCHandleWS.upload);
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BlueToothUtil.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                boolean b = mBluetoothLeService.setNotificationWay();
                if (!b) {
                    showTrip("请选择正确的标签设备");
                    SPUtils.remove(mContext, GlobalData.Ble_Device_Mac);
                }else{
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("连接设备成功");
                    //                    }
                }
                LogUtil.i("","mBluetoothLeService.setNotificationWay():" + b);
            } else if (BlueToothUtil.ACTION_TRANSFER_EXCEPTIONS.equals(action)) {
                showShortToast("激活失败，请稍后重试");
                finish();
                // showMyDialog(BlueToothUtil.DIALOG_TRANSFER_EXCEPTIONS);
            } else if (BlueToothUtil.ACTION_RESP_INIT_SUCCESS.equals(action)) {
                SendCmd(CMD_A2);
                //                if (GlobalData.isDebug) {
                loadingDialog.setTips("设备初始化成功");
                //                }
                // doNextState();//CONN_SUCCESS
                // onUIStateChangeListener.onStateChange(CONN_SUCCESS)
                LogUtil.i("","ACTION_RESP_INIT_SUCCESS");
            } else if (BlueToothUtil.ACTION_STATE_DISCONNECTED.equals(action)) {
                if (!isFinishing()) {
                    showShortToast("设备已与手机断开连接");
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 1000);
                }
                // showMyDialog(BlueToothUtil.DIALOG_STATE_DISCONNECTED);
            } else if (BlueToothUtil.ACTION_RECEIVCE_DATA_COMPLETE.equals(action)) {
                CmdReceiveData receiveData = (CmdReceiveData) intent.getExtras().getSerializable(BlueToothUtil.EXTRA_CMD_RECEIVCE_DATA);
                LogUtil.i("","ACTION_RECEIVCE_DATA_COMPLETE receiveData:" + receiveData.toString());
                int cmdType = receiveData.getCmdType();
                byte[] data = receiveData.getData();
                String dataStr = TopUpUtil.bytes2HexString(data);
                LogUtil.e("","CMD指令返回数据：" + dataStr);
                if (data != null && data.length > 1) {
                    if (data[1] != (byte) RESP_00) {
                        LogUtil.e("","!=" + RESP_00);
                        showTrip("指令执行失败，请稍后重试"+"\n"+"失败流程:"+cmdType+"\n"+"失败信息:"+dataStr);
                        errorUpload("指令执行失败，请稍后重试"+"\n"+"失败流程:"+cmdType+"\n"+"失败信息:"+dataStr);
                        return;
                    }
                } else {
                    showTrip("指令执行失败，请稍后重试"+"\n"+"失败流程:"+cmdType+"\n"+"失败信息:"+dataStr);
                    errorUpload("指令执行失败，请稍后重试"+"\n"+"失败流程:"+cmdType+"\n"+"失败信息:"+dataStr);
                }
                switch (cmdType) {
                    case CMD_A2:
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("设备握手成功");
                        //                        }
                        //                        if (data[0] != (byte) 0xb2) {
                        //                            LogUtils.e("!=" + 0xb2);
                        //                            return;
                        //                        }
                        int len = data[3];
                        len -= 5;
                        if (len > 80) {
                            LogUtil.i("","帧长度:" + len);
                            CmdHelper.initFrameLen(len, mContext);
                        }
                        //获取设备表面号
                        state = State.CMD_A5;
                        mBluetoothLeService.sendCmd(CMD_A5);
                        break;
                    case CMD_A5:
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("读取设备号成功");
                        //                        }
                        String c5Data = TopUpUtil.bytes2HexString(data);
                        String SEascii = c5Data.substring(8);
                       // seno = TopUpUtil.asciiToString(SEascii);
                        //LogUtils.i("设备表面号"+seno);
                        //获取0016文件
                        SendCmd(CMD_CARD_0016);
                        break;
                    case CMD_CARD_0016://卡0016文件
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("读取卡0016成功");
                        //                        }
                        file0016 = TopUpUtil.getInstructionResp(data);
                        get0016Info();
                        break;
                    case CMD_CARD_BALANCE:
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("读取卡余额成功");
                        //                        }
                        if (data[0] != (byte) 0xb3) {
                            LogUtil.e("","!=" + 0xb3);
                            return;
                        }
                        cardBalance = TopUpUtil.getCardBalance(data);
                        LogUtil.i("","card Balance:" + cardBalance);
                        //获取卡号（0015文件）
                        SendCmd(CMD_CARD_NUMBER);
                        break;
                    case CMD_CARD_NUMBER://0015
                        //                        if (GlobalData.isDebug) {
                        //                            loadingDialog.setTips("读取卡0015成功");
                        //                        }
                        if (data[0] != (byte) 0xb3) {
                            LogUtil.e("","!=" + 0xb3);
                            loadingDialog.setTips("获取卡信息失败，请稍后重试");
                            errorUpload("获取卡信息失败，请稍后重试");
                            return;
                        }
                        file0015 = TopUpUtil.getInstructionResp(data);
                        if (TextUtils.isEmpty(file0015)) {
                            loadingDialog.setTips("读取0015文件失败:"+file0015);
                            errorUpload("读取0015文件失败");
                            return;
                        }
                        if (file0015.length() > 12) {
                            //                            file0015 = file0015.substring(8, file0015.length() - 4);
                        }
                        loadingDialog.setTips("读取卡0015成功");
                        //TODO 获取卡号
                        LogUtil.i("","0015data:" + TopUpUtil.bytes2HexString(data));
                        // 卡网络编号 各省唯一
                        cardArea = TopUpUtil.getCardNumber(data).getCardArea();
                        LogUtil.i("","修改前，cardArea:" + cardArea);
                        //                        if (!GlobalData.cardArea.equals(cardArea)) {
                        //                            DialogHelper.showComfirmDialog(mContext, "取消", "确定", "激活设备只支持辽通卡",
                        //                                    new ComfirmDialog.DialogOnclick() {
                        //                                        @Override
                        //                                        public void PerDialogclick(ComfirmDialog dialog) {
                        //                                            dialog.dismiss();
                        //                                            finish();
                        //                                        }
                        //                                    }, new ComfirmDialog.DialogOnclick() {
                        //                                        @Override
                        //                                        public void PerDialogclick(ComfirmDialog dialog) {
                        //                                            dialog.dismiss();
                        //                                            finish();
                        //                                        }
                        //                                    });
                        //                        }
                        cardNo = TopUpUtil.getCardNumber(data).getCardNumber();
                        plateNo = TopUpUtil.getCardNumber(data).getPlateNum();

                        if (isActivationSuccess) {
                            loadingDialog.dismiss();
                            showShortToast("激活成功");
                            String cardNew=cardArea+cardNo;
                            activationSuccess(cardNew);
                            finish();
                        }else {
                            if (!TextUtils.isEmpty(cardNo)) {
                                String cardType = cardNo.substring(4, 6);
                                if ("23".equals(cardType)) {
                                    //                                tvCardType.setText(getResources().getString(R.string.card_type) + "记账卡");
                                } else {
                                    //                                tvCardType.setText(getResources().getString(R.string.card_type) + "储值卡");
                                }
                            }

                            SendCmd(CMD_OBU_SYSTEM_INFO);
                        }
                        break;
                    case CMD_OBU_SYSTEM_INFO://OBU系统信息 EF01
                        //                        if (GlobalData.isDebug) {
                        //                        }
                        fileSystem = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(fileSystem)&&fileSystem.length()>44) {
                            loadingDialog.setTips("读取obu系统信息成功");
                            seno=fileSystem.substring(28,44);
                            //fileSystem = fileSystem.substring(8, fileSystem.length() - 4);
                            //合同版本号
                            //contractedition = fileSystem.substring(36, 38);

                            //                             seno = fileSystem.substring(28, 44);
                            //读取车辆信息(DF01-EF01)
                            state = State.CMD_OBU_CAR_INFO;
                            SendCmd(CMD_OBU_CAR_INFO);
                        }else{
                            loadingDialog.setTips("读取obu系统信息失败："+fileSystem);
                        }
                        break;
                    case CMD_OBU_CAR_INFO://obu车辆信息 DF01-EF01
                        filevehicle = TopUpUtil.getInstructionResp(data);
                        //                        if (GlobalData.isDebug) {
                        //                        }
                        if (!TextUtils.isEmpty(filevehicle) && filevehicle.length() > 12) {
                            loadingDialog.setTips("读取OBU车辆信息成功");
                            //                            filevehicle = filevehicle.substring(8, filevehicle.length() - 4);
                            loadingDialog.setTips("正在发行设备");
//                            if (GlobalData.isDebug) {
//                                orderno = etOrderNo.getText().toString().trim();
//                            }
                            cardNo = cardArea + cardNo;

                            if (!TextUtils.isEmpty(type)) {
                                SendCmd(CMD_OBU_RANDOM);

                            }else {
                                if (isEndSureSuccess){
                                    //showTrip("激活成功");
                                    SendCmd(CMD_OBU_RANDOM);
                                }else {
                                    //                                if (GlobalData.isDebug) {
                                    loadingDialog.setTips("查询是否可以激活");
                                    //                                }
                                    //查询是否可以激活
                                    doRequest(ActivateWS.canActivate, ActivateWS.canActivateParams(ticketid,orderno, cardNo, seno), ActivateWS.canActivate);
                                }
                            }
                        }else{
                            loadingDialog.setTips("读取OBU车辆信息失败："+filevehicle);
                        }
                        break;

                    case CMD_C4:
                        String c4Data = TopUpUtil.bytes2HexString(data);
                        if (!TextUtils.isEmpty(c4Data)) {
                            LogUtil.e("","CMD_C4---" + c4Data);
                            String SE = c4Data.substring(10, 26);
                            String R1 = c4Data.substring(26, 58);
                            String S1 = c4Data.substring(58, c4Data.length() - 2);
                            String A1 = c4Data.substring(c4Data.length() - 2);
                            //国密握手
                            authGm(SE,R1,S1,A1);
                        }else{
                            showShortToast("C4指令执行失败");
                            errorUpload("C4指令执行失败");
                        }
                        break;
                    case CMD_C5:
                        if (data[0] != (byte) 0xb6) {
                            LogUtil.e("","!=" + 0xb6);
                            return;
                        }
                        switch (startstate) {//取随机数
                            case "0":
                                SendCmd(CMD_GM_OBU_RANDOM, instructions + instructionsmac);
                                //                                SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                                break;
                            case "1":
                                SendCmd(CMD_GM_OBU_RANDOM, instructions + instructionsmac);
                                break;
                            case "2":
                                SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                                break;
                            case "3":
                                SendCmd(CMD_GM_CARD_RANDOM, instructions + instructionsmac);
                                break;
                        }
                        break;
                    case CMD_GM_OBU_RANDOM:
                        String gmOBURandom = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gmOBURandom)) {
                            instructionresps = gmOBURandom.substring(0, gmOBURandom.length() - 8);
                            instructionrespsmac = gmOBURandom.substring(gmOBURandom.length() - 8);
                            state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                            if ("0".equalsIgnoreCase(startstate)) {
                                gmModifyVehicle();
                            } else if ("1".equalsIgnoreCase(startstate)) {
                                gmModifySystem();
                            }
                        }
                        break;
                    case CMD_GM_CARD_RANDOM:
                        String gmCardRandom = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gmCardRandom)) {
                            instructionresps = gmCardRandom.substring(0, gmCardRandom.length() - 8);
                            instructionrespsmac = gmCardRandom.substring(gmCardRandom.length() - 8);
                            state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                            if ("2".equalsIgnoreCase(startstate)) {
                                gmModify0016();
                            } else if ("3".equalsIgnoreCase(startstate)) {
                                gmModify0015();
                            }
                        }
                        break;
                    case CMD_OBU_RANDOM:
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("读取OBU随机数成功");
                        //                        }
                        //                        randomObu = TopUpUtil.bytes2HexString(data).substring(18, 26);
                        randomObu = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(randomObu)) {
                            randomObu = randomObu.toUpperCase();
                            if (!TextUtils.isEmpty(type)){
                                //obu激活
                                Bundle bundle = new Bundle();
                                bundle.putString("fileSystem", fileSystem);
                                bundle.putString("fileVehicle", filevehicle);
                                bundle.putString("file0015", file0015);
                                bundle.putString("obuNo", seno);
                                bundle.putString("cardBalance", cardBalance);
                                bundle.putString("randomObu", randomObu);
                                openActivity(OBUQueryInfoActivity.class,bundle);
                                loadingDialog.dismiss();
                                finish();
                                return;
                            }
                            if (isEndSureSuccess){
                                issueEnd();
                            }else {
                                modifyVehicle();
//                                startstate = "0";
//                                mSessionId = "d79839614e3aeaac015048a114b1541a";
//                                SendCmd(CMD_OBU_MODIFY_VEHICLE, "8067014404D681003FBCAA4139334D453000000000000001000000000000000000000005000000000000000000000000000000004C3330353136380000000000000000000E34A9F2020f00b400000a00000000000000003b00030700a40000023f0004050084000004");
                            }
                        }
                        break;
                    case CMD_GM_OBU_MODIFY_VEHICLE:
                        String gmVehicleResult = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gmVehicleResult)) {
                            instructionresps = gmVehicleResult.substring(0, gmVehicleResult.length() - 8);
                            instructionrespsmac = gmVehicleResult.substring(gmVehicleResult.length() - 8);
                            state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                            gmModifySystem();
                        }
                        break;
                    case CMD_GM_OBU_MODIFY_SYSTEM:
                        String gmSystemResult = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gmSystemResult)) {
                            instructionresps = gmSystemResult.substring(0, gmSystemResult.length() - 8);
                            instructionrespsmac = gmSystemResult.substring(gmSystemResult.length() - 8);
                            SendCmd(CMD_TO_3F00);
                        }
                        break;
                    case CMD_GM_CARD_MODIFY_0016:
                        String gm0016Result = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gm0016Result)) {
                            instructionresps = gm0016Result.substring(0, gm0016Result.length() - 8);
                            instructionrespsmac = gm0016Result.substring(gm0016Result.length() - 8);
                            state = State.CMD_GM_CARD_MODIFY_0015;
                            gmModify0015();
                        }
                        break;
                    case CMD_GM_CARD_MODIFY_0015:
                        String gm0015Result = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(gm0015Result)) {
                            instructionresps = gm0015Result.substring(0, gm0015Result.length() - 8);
                            instructionrespsmac = gm0015Result.substring(gm0015Result.length() - 8);
                            state = State.CMD_OBU_MODIFY_SYSTEM;
                            gmIssueEnd();
                        }
                        break;
                    case CMD_OBU_MODIFY_VEHICLE:
                        String vehicleResult = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(vehicleResult)) {
                            instructionresps = vehicleResult;
                            switch (startstate) {
                                case "0":
                                case "1":
                                    modifySystem();
                                    break;
                                case "2":
                                    modify0016();
                                    break;
                                case "3":
                                    modify0015();
                                    break;
                            }

                        }
                        break;
                    case CMD_CARD_MODIFY_INFO:
                        String modifyInfo = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(modifyInfo)) {
                            instructionresps = modifyInfo;
                            if ("2".equalsIgnoreCase(startstate)) {
                                modify0016();
                            } else if ("3".equalsIgnoreCase(startstate)) {
                                modify0015();
                            }
                        }
                        break;
                    case CMD_OBU_MODIFY_SYSTEM:
                        String systemResult = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(systemResult)) {
                            //跳转3F00目录
                            SendCmd(CMD_TO_3F00);
                            instructionresps = systemResult;
                        }
                        break;
                    case CMD_TO_3F00:
                        //                        randomCard = TopUpUtil.bytes2HexString(data).substring(18, 26);
                        randomCard = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(randomCard)) {
                            randomCard = randomCard.toUpperCase();
                            if (isGm) {
                                state = State.CMD_GM_CARD_MODIFY_0016;
                                gmModify0016();
                            }else {
                                state = State.CMD_CARD_MODIFY_0016;
                                modify0016();
                            }
                        }
                        break;
                    case CMD_CARD_MODIFY_0016:
                        String card0016Result = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(card0016Result)) {
                            instructionresps = card0016Result;
                            state = State.CMD_CARD_MODIFY_0015;
                            modify0015();
                        }
                        break;
                    case CMD_CARD_MODIFY_0015:
                        String card0015Result = TopUpUtil.getInstructionResp(data);
                        if (!TextUtils.isEmpty(card0015Result)) {
                            instructionresps = card0015Result;
                            state = State.CMD_GM_OBU_MODIFY_SYSTEM;
                            isEndSureSuccess=true;
                            SendCmd(CMD_CARD_0016);
                        }
                        break;
                }
            }
        }
    };

    private void get0016Info() {
        if (!TextUtils.isEmpty(file0016)&&file0016.length()>12) {
            //                            file0016 = file0016.substring(8, file0016.length() - 4);
            state = State.CMD_CARD_GET_0015;
            //获取卡余额
            SendCmd(CMD_CARD_BALANCE);
        }else{
            showShortToast("获取0015文件失败");
            errorUpload("获取0015文件失败");
        }
    }

    private void showTrip(String trip) {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
        tripDialog.setTrips(trip);
        tripDialog.show();
    }

    private void showErrorMsg(String dataStr) {
        if (loadingDialog.isShowing()) {
            if (GlobalData.isDebug) {
                loadingDialog.setTips("激活失败");
                errorUpload("激活失败:" + dataStr);
            }
            loadingDialog.dismiss();
            showLongToast("激活失败");
            errorUpload("激活失败" + dataStr);
        }
        // showMyDialog(DIALOG_TRANSFER_EXCEPTIONS);
    }

    private void authGm(String SE, String R1, String S1, String A1) {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用国密握手接口");
        //        }
        state = State.CMD_AUTHGM;
        doRequest(ActivateWS.authgm,ActivateWS.authgmParams(
                orderno,seno,SE,R1,S1,filevehicle,fileSystem,file0016,file0015),ActivateWS.authgm);
    }

    //获取国密标签二发更新车辆信息文件
    private void gmModifyVehicle() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统车辆文件接口");
        //        }
        doRequest(ActivateWS.gmModifyVehicle,
                ActivateWS.gmModifyVehicleParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModifyVehicle);
    }

    private void gmModifySystem() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统信息文件接口");
        //        }
        doRequest(ActivateWS.gmModifySystem,
                ActivateWS.gmModifySystemParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModifySystem);
    }

    private void gmModify0016(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0016文件接口");
        //        }else {
        //            loadingDialog.setTips("正在发行卡片");
        //        }
        doRequest(ActivateWS.gmModify0016,
                ActivateWS.gmModify0016Params(mSessionId,randomCard,instructionresps,instructionrespsmac),
                ActivateWS.gmModify0016);
    }

    private void gmModify0015(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0015文件接口");
        //        }
        doRequest(ActivateWS.gmModify0015,
                ActivateWS.gmModify0015Params(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmModify0015);
    }

    private void gmIssueEnd(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用完成接口");
        //        }
        doRequest(ActivateWS.gmIssueEnd,
                ActivateWS.gmIssueEndParams(mSessionId,instructionresps,instructionrespsmac),
                ActivateWS.gmIssueEnd);
    }

    //获取明文标签二发更新车辆信息文件
    private void modifyVehicle() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统车辆文件接口");
        //        }
        doRequest(ActivateWS.modifyVehicle,
                ActivateWS.modifyVehicleParams(
                        orderno, randomObu,filevehicle,
                        fileSystem,file0016,file0015,
                        seno,deviceuuid,ticketid),
                ActivateWS.modifyVehicle);
        /*doRequest(ActivateWS.decodeinstructions11,
                ActivateWS.decodeinstructions11(
                        randomObu,filevehicle,
                        fileSystem,
                        seno),
                ActivateWS.decodeinstructions11);*/
    }

    private void modifySystem() {
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改系统信息文件接口");
        //        }
        doRequest(ActivateWS.modifySystem,
                ActivateWS.modifySystemParams(mSessionId, instructionresps),
                ActivateWS.modifySystem);
    }

    private void modify0016(){
        //TODO
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0016文件接口");
        //        }else {
        //            loadingDialog.setTips("正在发行卡片");
        //        }
        doRequest(ActivateWS.modify0016,
                ActivateWS.modify0016Params(mSessionId, randomCard, instructionresps),
                ActivateWS.modify0016);
    }

    private void modify0015(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("调用修改卡0015文件接口");
        //        }
        doRequest(ActivateWS.modify0015,
                ActivateWS.modify0015Params(mSessionId, instructionresps),
                ActivateWS.modify0015);
    }

    private void issueEnd(){
        //        if (GlobalData.isDebug) {
        loadingDialog.setTips("激活成功 调用完成接口");
        //        }
        doRequest(ActivateWS.issueEnd,
                ActivateWS.issueEndParams(ticketid, mSessionId, instructionresps,filevehicle,fileSystem,file0016,file0015,randomObu),
                ActivateWS.issueEnd);
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(result);
            if (JsonUtil.GetJsonStatu00(jsonObject)) {
                if (ActivateWS.canActivate.equalsIgnoreCase(id)) {
                    //                CanActivateMDL activateMDL = JsonUtil.fromJson(jsonObject, CanActivateMDL.class);
                    //                if (activateMDL != null) {
                    if (isGm) {
                        //发送A6-C4指令
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送C4指令");
                        //                        }
                        SendCmd(CMD_C4);
                    }else{
                        //读取标签车辆文件 读取标签随机数
                        //获取obu系统信息文件（EF01）
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送获取随机数指令");
                        //                        }
                        SendCmd(CMD_OBU_RANDOM);
                    }
                    //                }
                } else if (ActivateWS.authgm.equalsIgnoreCase(id)) {
                    AuthgmMDL authgmMDL = JsonUtil.fromJson(jsonObject, AuthgmMDL.class);
                    if (authgmMDL != null) {
                        startstate = authgmMDL.getStartstate();
                        mSessionId = authgmMDL.getSessionid();
                        if (TextUtils.isEmpty(startstate) || TextUtils.isEmpty(mSessionId)) {
                            loadingDialog.dismiss();
                            showShortToast("获取数据失败，请稍后重试");
                            return;
                        }
                        if ("4".equalsIgnoreCase(startstate)) {
                            gmIssueEnd();
                            return;
                        }
                        instructions = authgmMDL.getInstructions();
                        instructionsmac = authgmMDL.getInstructionsmac();
                        // C5+工作密钥密文+工作密钥校验值（8字节）+MAC密钥密文+MAC密钥校验值（8字节）+Rnd2（16字节）+S2
                        // String workkey, String workkeyMac, String mackey, String
                        // mackeyMac, String random2,String signdata
                        String[] params = new String[6];
                        params[0] = authgmMDL.getWorkkey();
                        // LogUtils.i("workkey:"+params[0]);
                        params[1] = authgmMDL.getWorkkeymac();
                        // LogUtils.i("workkeyMac:"+params[1]);
                        params[2] = authgmMDL.getMackey();
                        // LogUtils.i("mackey:"+params[2]);
                        params[3] = authgmMDL.getMackeymac();
                        // LogUtils.i("mackeyMac:"+params[3]);
                        params[4] = authgmMDL.getRandom2();
                        // LogUtils.i("random2:"+params[4]);
                        params[5] = authgmMDL.getSigndata();
                        // LogUtils.i("signdata:"+params[5]);
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送C5指令");
                        //                        }
                        SendCmd(CMD_C5, params);
                        // mBluetoothLeService.sendVerifyCmd(CMD_C5, params);
                    }else{
                        showShortToast("国密握手失败");
                        errorUpload("国密握手失败");
                    }

                    /**国密流程*/
                } else if (ActivateWS.gmModifyVehicle.equalsIgnoreCase(id)) {
                    ModifyActivationMDL vehicleMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (vehicleMDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改车辆信息文件接口");
                        //                        }
                        if (!TextUtils.isEmpty(vehicleMDL.getInstructions())) {
                            SendCmd(CMD_GM_OBU_MODIFY_VEHICLE, vehicleMDL.getInstructions() + vehicleMDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmModifySystem.equalsIgnoreCase(id)) {
                    ModifyActivationMDL systemMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (systemMDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改系统信息文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(systemMDL.getInstructions())) {
                            SendCmd(CMD_GM_OBU_MODIFY_SYSTEM, systemMDL.getInstructions() + systemMDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmModify0016.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modify0016MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0016MDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改卡0016文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(modify0016MDL.getInstructions())) {
                            SendCmd(CMD_GM_CARD_MODIFY_0016, modify0016MDL.getInstructions() + modify0016MDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmModify0015.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modify0015MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0015MDL != null) {
                        //                        if (GlobalData.isDebug) {
                        loadingDialog.setTips("发送修改卡0015文件指令");
                        //                        }
                        if (!TextUtils.isEmpty(modify0015MDL.getInstructions())) {
                            SendCmd(CMD_GM_CARD_MODIFY_0015, modify0015MDL.getInstructions() + modify0015MDL.getInstructionsmac());
                        }
                    }
                } else if (ActivateWS.gmIssueEnd.equalsIgnoreCase(id)) {
                    isActivationSuccess = true;
                    //获取卡号（0015文件） 查询卡号车牌号
                    SendCmd(CMD_CARD_NUMBER);
                    /**明文*/
                } else if (ActivateWS.modifyVehicle.equalsIgnoreCase(id)) {
                    ModifyActivationMDL modifyVehicleMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modifyVehicleMDL != null) {
                        startstate = modifyVehicleMDL.getStartstate();
                        mSessionId = modifyVehicleMDL.getSessionid();
                        if (TextUtils.isEmpty(startstate) || TextUtils.isEmpty(mSessionId)) {
                            loadingDialog.dismiss();
                            showShortToast("获取数据失败，请稍后重试");
                            return;
                        }
                        if ("4".equalsIgnoreCase(startstate)) {
                            issueEnd();//4：不执行指令，直接调用发行结束
                            return;
                        }
                        if (!TextUtils.isEmpty(modifyVehicleMDL.getInstructions())) {
                            switch (startstate) {
                                case "0":
                                case "1":
                                    //                                    if (GlobalData.isDebug) {
                                    loadingDialog.setTips("发送修改车辆信息文件接口");
                                    //                                    }
                                    SendCmd(CMD_OBU_MODIFY_VEHICLE, modifyVehicleMDL.getInstructions());
                                    break;
                                case "2":
                                case "3":
                                    SendCmd(CMD_CARD_MODIFY_INFO, modifyVehicleMDL.getInstructions());
                                    break;
                            }
                        }else {
                            showTrip("获取写车辆信息指令失败");
                        }
                    }else {
                        showTrip("获取写车辆信息指令失败");
                    }
                } else if (ActivateWS.modifySystem.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改系统信息文件指令");
                    //                    }
                    ModifyActivationMDL modifySystemMDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modifySystemMDL != null) {
                        if (!TextUtils.isEmpty(modifySystemMDL.getInstructions())) {
                            SendCmd(CMD_OBU_MODIFY_SYSTEM, modifySystemMDL.getInstructions());
                        }else {
                            showTrip("获取写系统信息指令失败");
                        }
                    }else {
                        showTrip("获取写系统信息指令失败");
                    }
                } else if (ActivateWS.modify0016.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改卡0016文件指令");
                    //                    }
                    ModifyActivationMDL modify0016MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0016MDL != null) {
                        if (!TextUtils.isEmpty(modify0016MDL.getInstructions())) {
                            SendCmd(CMD_CARD_MODIFY_0016, modify0016MDL.getInstructions());
                        }else {
                            showTrip("获取写0016指令失败");
                        }
                    }else {
                        showTrip("获取写0016指令失败");
                    }
                } else if (ActivateWS.modify0015.equalsIgnoreCase(id)) {
                    //                    if (GlobalData.isDebug) {
                    loadingDialog.setTips("发送修改卡0015文件指令");
                    //                    }
                    ModifyActivationMDL modify0015MDL = JsonUtil.fromJson(jsonObject, ModifyActivationMDL.class);
                    if (modify0015MDL != null) {
                        if (!TextUtils.isEmpty(modify0015MDL.getInstructions())) {
                            SendCmd(CMD_CARD_MODIFY_0015, modify0015MDL.getInstructions());
                        }else {
                            showTrip("获取写0015指令失败");
                        }
                    }else {
                        showTrip("获取写0015指令失败");
                    }
                } else if (ActivateWS.issueEnd.equalsIgnoreCase(id)) {
                    isActivationSuccess = true;
                    //获取卡号（0015文件） 查询卡号车牌号
                    SendCmd(CMD_CARD_NUMBER);
                }
            }else{
                loadingDialog.dismiss();
                showTrip("温馨提示："+JsonUtil.GetErrorString(jsonObject, "msg"));
                //                errorUpload(JsonUtil.GetErrorString(jsonObject, "msg"));
                //                showLongToast(JsonUtil.GetErrorString(jsonObject, "msg"));
                //                SendCmd(CMD_C3);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            loadingDialog.dismiss();
            showTrip("数据解析异常：" + result);
        }
    }


    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        loadingDialog.dismiss();
        //        showShortToast("系统繁忙，请稍后重试");
        //        SendCmd(CMD_C3);
        //        showTrip("系统繁忙，请稍后重试");
    }

    @Override
    public void OnHttpFailure(String type, String errorMsg) {
        super.OnHttpFailure(type, errorMsg);
        loadingDialog.dismiss();
        //        showShortToast("系统繁忙，请稍后重试");
        //        SendCmd(CMD_C3);
        showTrip("服务器异常\nurl:"+type+"\nmsg:" + errorMsg);
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        loadingDialog.dismiss();
        //        showShortToast("网络异常，请检查网络");
        //        SendCmd(CMD_C3);
        showTrip("网络繁忙，请检查网络");
    }

    private void activationSuccess(String cardNew) {
        Bundle bundle = getIntent().getExtras();
        bundle.putString("plateNo", plateNo);
        bundle.putString("cardNo",cardNew);
//        openActivity(ETCActivationSuccessActivity.class, bundle);
    }


    private void SendCmd(int cmd) {
        SendCmd(cmd, "");
    }

    private void SendCmd(int cmd, String... params) {
        // if(numOfReSend >= RESEND_LIMIT){
        // //超过尝试次数，不再发送命令
        // ToastUtil.showShort(mContext,"指令多次发送无回复，请重试");
        // return;
        // }
        // numOfReSend ++;
        // uiThreadHandler.removeCallbacks(runable);
        // isReceiveData = false;
        switch (cmd) {
            case CMD_C4:
                state = State.CMD_C4;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendCmd(CMD_C4);
                break;
            case CMD_A2:
                state = State.CMD_A2;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendCmd(CMD_A2);
                break;
            case CMD_TO_3F00:
                state = State.CMD_TO_3F00;
                mBluetoothLeService.sendDirectCmd(CMD_TO_3F00,isJuLi);
                break;
            case CMD_CARD_0016:
                state = State.CMD_CARD_GET_0016;
                mBluetoothLeService.sendDirectCmd(CMD_CARD_0016,isJuLi);
                break;
            case CMD_CARD_BALANCE:
                state = State.CMD_CARD_BALANCE;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendDirectCmd(CMD_CARD_BALANCE,isJuLi);
                break;
            case CMD_CARD_NUMBER:
                state = State.CMD_CARD_GET_0015;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendDirectCmd(CMD_CARD_NUMBER,isJuLi);
                break;
            case CMD_CARD_PIN0:
                state = State.CMD_CARD_PIN0;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendDirectCmd(CMD_CARD_PIN0,isJuLi);
                break;
            case CMD_CARD_PIN3:
                state = State.CMD_CARD_PIN3;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendDirectCmd(CMD_CARD_PIN3,isJuLi);
                break;
            case CMD_CARD_PIN6:
                state = State.CMD_CARD_PIN6;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendDirectCmd(CMD_CARD_PIN6,isJuLi);
                break;
            case CMD_C5:
                state = State.CMD_C5;
                // uiThreadHandler.postDelayed(runable, RECEIVE_TIME_LIMIT);
                mBluetoothLeService.sendVerifyCmd(CMD_C5,isJuLi, params);
                break;
            case CMD_OBU_SYSTEM_INFO:
                state = State.CMD_OBU_SYSTEM_INFO;
                mBluetoothLeService.sendDirectCmd(CMD_OBU_SYSTEM_INFO,isJuLi);
                break;
            case CMD_OBU_CAR_INFO:
                state = State.CMD_OBU_CAR_INFO;
                mBluetoothLeService.sendDirectCmd(CMD_OBU_CAR_INFO,isJuLi);
                break;
            case CMD_OBU_RANDOM:
                state = State.CMD_OBU_RANDOM;
                mBluetoothLeService.sendDirectCmd(CMD_OBU_RANDOM,isJuLi);
                break;
            case CMD_CARD_MODIFY_INFO:
                state = State.CMD_CARD_RANDOM;
                if (params.length > 0 && !TextUtils.isEmpty(params[0])) {
                    mBluetoothLeService.sendVerifyCmd(CMD_CARD_MODIFY_INFO,isJuLi, params);
                }else {
                    mBluetoothLeService.sendDirectCmd(CMD_CARD_MODIFY_INFO,isJuLi);
                }
                break;
            case CMD_GM_OBU_RANDOM:
                state = State.CMD_GM_OBU_RANDOM;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_OBU_RANDOM,isJuLi,params);
                break;
            case CMD_GM_CARD_RANDOM:
                state = State.CMD_GM_CARD_RANDOM;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_CARD_RANDOM,isJuLi,params);
                break;
            case CMD_GM_OBU_MODIFY_VEHICLE:
                state = State.CMD_OBU_MODIFY_VEHICLE;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_OBU_MODIFY_VEHICLE,isJuLi, params);
                break;
            case CMD_GM_OBU_MODIFY_SYSTEM:
                state = State.CMD_OBU_MODIFY_SYSTEM;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_OBU_MODIFY_SYSTEM,isJuLi, params);
                break;
            case CMD_GM_CARD_MODIFY_0016:
                state = State.CMD_CARD_MODIFY_0016;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_CARD_MODIFY_0016,isJuLi, params);
                break;
            case CMD_GM_CARD_MODIFY_0015:
                state = State.CMD_CARD_MODIFY_0015;
                mBluetoothLeService.sendVerifyCmd(CMD_GM_CARD_MODIFY_0015,isJuLi, params);
                break;

            case CMD_OBU_MODIFY_VEHICLE:
                state = State.CMD_OBU_MODIFY_VEHICLE;
                mBluetoothLeService.sendVerifyCmd(CMD_OBU_MODIFY_VEHICLE,isJuLi, params);
                break;
            case CMD_OBU_MODIFY_SYSTEM:
                state = State.CMD_OBU_MODIFY_SYSTEM;
                mBluetoothLeService.sendVerifyCmd(CMD_OBU_MODIFY_SYSTEM,isJuLi, params);
                break;
            case CMD_CARD_MODIFY_0016:
                state = State.CMD_CARD_MODIFY_0016;
                mBluetoothLeService.sendVerifyCmd(CMD_CARD_MODIFY_0016,isJuLi, params);
                break;
            case CMD_CARD_MODIFY_0015:
                state = State.CMD_CARD_MODIFY_0015;
                mBluetoothLeService.sendVerifyCmd(CMD_CARD_MODIFY_0015,isJuLi, params);
                break;
        }
    }

}
